package com.starsky.common.utils.encrypt;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

/**
 * @desc: triple加密
 * @author: wangsh
 */
public class TripleDesUtils {
    private static final String KEY_ALGORITHM = "DESede";
    private static final String CIPHER_ALGORITHM_ECB = "DESede/ECB/PKCS5Padding";
    private static final String CIPHER_ALGORITHM_CBC = "DESede/CBC/PKCS5Padding";
    private static final String ENCODING = "UTF-8";
    private String keySeed = "0123456789zxcv0123456789";
    private SecretKey secretKey;
    private Cipher cipher;

    public TripleDesUtils() throws Exception {
        this("ECB");
    }

    public TripleDesUtils(String mode) throws Exception {
        this.secretKey = new SecretKeySpec(this.keySeed.getBytes("UTF-8"), "DESede");

        if ("ECB".equals(mode)) {
            this.cipher = Cipher.getInstance("DESede/ECB/PKCS5Padding");
        } else if ("CBC".equals(mode)) {
            this.cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
        }
    }

    /**
     * 加密
     * @param str
     * @return
     * @throws Exception
     */
    public synchronized byte[] encrypt(String str)throws Exception {
        this.cipher.init(1, this.secretKey);
        return this.cipher.doFinal(str.getBytes());
    }

    /**
     * 解密
     * @param encrypt
     * @return
     * @throws Exception
     */
    public synchronized byte[] decrypt(byte[] encrypt)
            throws Exception {
        this.cipher.init(2, this.secretKey);
        return this.cipher.doFinal(encrypt);
    }

    private byte[] getIV(String iv) throws Exception {
        String thisIV = iv;
        if (thisIV == null) {
            thisIV = "12345678";
        }
        return thisIV.getBytes("UTF-8");
    }

    public synchronized byte[] encrypt_cbc(String str)throws Exception {
        this.cipher.init(1, this.secretKey,
                new IvParameterSpec(getIV("12345678")));

        return this.cipher.doFinal(str.getBytes("utf-8"));
    }

    public synchronized byte[] decrypt_cbc(byte[] encrypt)throws Exception {
        this.cipher.init(2, this.secretKey,
                new IvParameterSpec(getIV("12345678")));

        return this.cipher.doFinal(encrypt);
    }

    public String getKeySeed() {
        return this.keySeed;
    }

    public void setKeySeed(String keySeed) throws Exception {
        this.keySeed = keySeed;
        this.secretKey = new SecretKeySpec(keySeed.getBytes("UTF-8"), "DESede");
    }

}
